package com.freemarker.test;

import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;


public class FreemarkerUtils {
	private static Configuration config = new Configuration();
	
	public static void processTemplate(String templateName,Map<?,?> root,Writer out){
		try {
			Template template = config.getTemplate(templateName,"utf-8");
			template.process(root, out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally{
			if(null != out){
				try {
					out.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void initConfig(ServletContext context,String templateDir){
		config.setLocale(Locale.CHINA);
		config.setDefaultEncoding("utf-8");
		config.setEncoding(Locale.CHINA, "utf-8");
		config.setServletContextForTemplateLoading(context, templateDir);
		config.setObjectWrapper(new DefaultObjectWrapper());
	}
}


